<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/4/24 16:06
 * Remark:
 */

namespace App\Http\Middleware\Auth;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Models\Auth\AuthBasicModel;
use App\Models\Auth\RoleModel;
use App\Models\Company\CompanyModel;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class AuthRoleLegitimacyMiddleware
{
    private RoleModel $_roleModel;
    private AuthBasicModel $_authBasicModel;

    public function __construct()
    {
        $this->_authBasicModel = new AuthBasicModel();
        $this->_roleModel = new RoleModel();
    }

    public function handle(\Illuminate\Http\Request $request, Closure $next): mixed
    {
        if(isset($request['auths'])){
            $this->IsExistsRole($request['role_id']);
            foreach($request['auths'] as $auth){
                $this->isExistsAuth($auth['auth_id']);
            }
        }
        return $next($request);
    }

    public function IsExistsRole($roleId){
        $isExists = $this->_roleModel->isExistByCondition([
           'role_id' => $roleId
        ]);
        if(!$isExists){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '当前角色'.$roleId.'不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

    public function isExistsAuth($authId){
        $isExists = $this->_authBasicModel->isExistByCondition([
            'auth_id' => $authId
        ]);
        if(!$isExists){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '当前权限'.$authId.'不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
    }

}